import { Request, Response } from 'express';
import { adminUserService } from './service';
import { Like } from 'typeorm';
import { ApiResponse } from '../../types/page';
import { AdminUserListResponse } from './types';
import { AuthRequest } from '../../types/auth';
import logger from '../../utils/logger';

export const getAdminUsers = async (req: Request, res: Response) => {
    try {
        const current = Number(req.query.page) || 1;
        const size = Number(req.query.size) || 10;

        const whereQuery: any = {};
        if (req.query.username) {
            whereQuery.username = Like(`%${req.query.username}%`);
        }
        if (req.query.status) {
            whereQuery.status = req.query.status;
        }

        const { users, total } = await adminUserService.findAll({
            ...whereQuery,
            page: current,
            pageSize: size,
        });

        const response: ApiResponse<AdminUserListResponse> = {
            success: true,
            data: {
                records: users.map(user => ({
                    ...user,
                })),
                total,
                size,
                current,
                pages: Math.ceil(total / size)
            }
        };

        res.json(response);
    } catch (error: any) {
        res.json({
            success: false,
            message: '获取管理员用户列表失败',
            error: error.message
        });
    }
};

export const getAdminUserById = async (req: Request, res: Response) => {
    try {
        const user = await adminUserService.findById(Number(req.params.id));
        if (!user) {
            return res.status(404).json({ success: false, message: '管理员用户不存在' });
        }
        res.json({ success: true, data: user });
    } catch (error) {
        res.status(500).json({ success: false, message: '获取管理员用户信息失败', error });
    }
};

export const createAdminUser = async (req: Request, res: Response) => {
    try {
        const user = await adminUserService.create(req.body);
        res.json({ success: true, data: user });
    } catch (error: any) {
        res.status(error.status || 500).json({
            success: false,
            message: error.message || '创建管理员用户失败'
        });
    }
};

export const updateAdminUser = async (req: Request, res: Response) => {
    try {
        const user = await adminUserService.update(Number(req.params.id), req.body);
        if (!user) {
            return res.status(404).json({ success: false, message: '管理员用户不存在' });
        }
        res.json({ success: true, data: user });
    } catch (error: any) {
        res.status(error.status || 500).json({
            success: false,
            message: error.message || '更新管理员用户失败'
        });
    }
};

export const deleteAdminUser = async (req: Request, res: Response) => {
    try {
        const result = await adminUserService.delete(Number(req.params.id));
        if (!result) {
            return res.status(404).json({ success: false, message: '管理员用户不存在' });
        }
        res.json({ success: true, message: '删除成功' });
    } catch (error) {
        res.status(500).json({ success: false, message: '删除管理员用户失败', error });
    }
};

/**
 * 更新管理员用户头像
 * @param req 请求对象，需要在body中包含avatarUrl字段
 * @param res 响应对象
 */
export const updateAvatar = async (req: AuthRequest, res: Response) => {
    try {
        const { avatarUrl } = req.body;
        const userId = Number(req.user?.id);

        if (!userId) {
            return res.status(400).json({
                success: false,
                message: '未提供用户ID'
            });
        }

        if (!avatarUrl) {
            return res.status(400).json({
                success: false,
                message: '头像URL不能为空'
            });
        }
        logger.info(`更新用户头像：userId=${userId}, avatarUrl=${avatarUrl}`);

        // 更新用户头像
        const user = await adminUserService.update(userId, { avatar: avatarUrl });

        if (!user) {
            return res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }

        res.json({
            success: true,
            message: '头像更新成功',
            data: {
                userId,
                avatar: avatarUrl
            }
        });
    } catch (error: any) {
        logger.error('更新头像失败:', error);
        res.status(500).json({
            success: false,
            message: '更新头像失败',
            error: error.message || String(error)
        });
    }
}; 